from xml.etree import ElementTree as et


# 修改、新增XML
class BaseElement:

    def __init__(self, xml_path):
        self.xml_path = xml_path
        self.root = et.parse(self.xml_path).getroot()


class AirConfig(BaseElement):

    def __init__(self, xml_path):
        super(AirConfig, self).__init__(xml_path)
        self.obj_xml = et.parse(self.xml_path)
        self.xml_airport = self.obj_xml.getroot()
        self.__airport = []
        self.__find_airport()

    def set_local_airport(self, airport: str):
        """
        修改本场四字码
        @param airport:
        @return:
        """
        # 转大写
        airport = airport.upper()
        __airport = self.xml_airport.find('LocalAirport')
        if airport not in self.__airport.keys():
            return f"{airport} 未配置场高参数！"
        if (airport != __airport.text
                and airport in [i['name'] for i in self.__airport.keys()]):
            __airport.text = airport
            return True

    def update_local_airport_info(self, airport, alt=None):
        """
        更新
        @param airport: 四字码
        @param alt: 场高
        @return:
        """
        obj_air_info = self.xml_airport.find('configs')
        if airport.upper() in obj_air_info.keys():
            pass

    def __find_airport(self):
        """
        查找本场的四字码
        @return:
        """
        __airports = self.xml_airport.find('configs')
        __air_info = {}
        for airport in __airports:
            __air_info['name'] = airport.get('name')
            __air_info['alt'] = airport.get('alt')
            self.__airport[airport] = __air_info
        print(self.__airport)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.obj_xml.write(self.xml_path, encoding='utf-8')
        print("保存")


if __name__ == '__main__':
    with AirConfig("./resources/base_airport_config.xml") as config:
        config.set_local_airport("ZUMY")
        config.update_local_airport_info("ZUUU")
